package com.cennavi.mm.service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.io.Serializable;

public class RandomCacheOper implements Serializable {
	// posMap
	public HashMap<String, Position> posMap = new HashMap<String, Position>();
	// randomCellFile
	private RandomAccessFile randomFile = null;
	// file length
	private long fileLength = 0;
	// 命中数
	public int hitNum = 0;
	// 命中数
	public int hitNotNum = 0;
	
	public RandomCacheOper(String file) {
		try {
			randomFile = new RandomAccessFile(file, "rw");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public byte[] getData(Position pos) {
//		Position pos = posMap.get(key);
		byte[] data = new byte[pos.length];
		try {
			randomFile.seek(pos.index);
			randomFile.read(data, 0, pos.length);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//更新命中率
		hitNum++;
		
		return data;
	}
	
	public void writeData(String key, byte[] data) {
		//写入数据
		try {
			randomFile.seek(fileLength);
			randomFile.write(data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
		//加入缓存
		Position pos = new Position();
		pos.index = fileLength;
		pos.length = data.length;
		posMap.put(key, pos);
		//更新文件长度
		fileLength = fileLength + data.length;
		//更新命中率
		hitNotNum++;
	}
	
	public void close() {
		try {
			randomFile.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
